<!--生产领料-->
<template>
  <div class="production-picking-container">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>关键词</label>
        <input type="text" v-model="searchForm.keyword" placeholder="请输入领料单号/工单编号">
      </div>
      <div class="filter-item">
        <label>审批状态</label>
        <select v-model="searchForm.approvalStatus">
          <option value="">全部</option>
          <option value="0">待审核</option>
          <option value="1">审核通过</option>
          <option value="2">审核驳回</option>
        </select>
      </div>
      <div class="filter-item">
        <label>申请人</label>
        <input type="text" v-model="searchForm.username" placeholder="请输入申请人">
      </div>
      <div class="filter-item">
        <label>日期范围</label>
        <input type="date" v-model="searchForm.startDate">
        <span>至</span>
        <input type="date" v-model="searchForm.endDate">
      </div>
      <div class="filter-buttons">
        <button class="btn-primary" @click="handleSearch">搜索</button>
        <button class="btn-secondary" @click="handleReset">重置</button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <button class="btn-primary" @click="handleAdd">新建</button>
      <button class="btn-danger" @click="handleBatchDelete" :disabled="selectedItems.length === 0">批量删除</button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>领料单号</th>
            <th>审批状态</th>
            <th>领料日期</th>
            <th>领料总数</th>
            <th>出库单</th>
            <th>生产工单</th>
            <th>申请人</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in pickingList" :key="item.id || index">
            <td><input type="checkbox" v-model="item.selected" @change="updateSelection"></td>
            <td>{{ item.requisition_no || item.requisitionNo || '-' }}</td>
            <td><span :class="statusClass(item.approval_status || item.approvalStatus)">{{ getStatusText(item.approval_status || item.approvalStatus) }}</span></td>
            <td>{{ formatDate(item.requisition_date || item.requisitionDate) }}</td>
            <td>{{ item.total_quantity || item.totalQuantity || '-' }}</td>
            <td>{{ item.warehouse_receipt || item.warehouseReceipt || '-' }}</td>
            <td>
              {{ item.production_work_order || item.productionWorkOrder || '-' }}
              <span class="work-order-code" v-if="item.production_work_order || item.productionWorkOrder">
                {{ item.production_work_order || item.productionWorkOrder }}
              </span>
            </td>
            <td>{{ item.username || '-' }}</td>
            <td>{{ item.remarks || '-' }}</td>
            <td>
              <button class="btn-link" @click="handleView(item)">查看</button>
              <button class="btn-link" @click="handleEdit(item)" v-if="(item.approval_status || item.approvalStatus) == 0">编辑</button>
              <button class="btn-link text-danger" @click="handleDelete(item)" v-if="(item.approval_status || item.approvalStatus) == 0">删除</button>
            </td>
          </tr>
          <tr v-if="loading">
            <td colspan="10" class="text-center">加载中...</td>
          </tr>
          <tr v-if="!loading && pickingList.length === 0">
            <td colspan="10" class="text-center">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination">
        <button @click="handlePageChange(pagination.current - 1)" :disabled="pagination.current <= 1">&lt;</button>
        <button 
          v-for="page in getPageNumbers()" 
          :key="page"
          :class="{ active: page === pagination.current }"
          @click="handlePageChange(page)"
        >
          {{ page }}
        </button>
        <button @click="handlePageChange(pagination.current + 1)" :disabled="pagination.current >= pagination.pages">&gt;</button>
        <select v-model="pagination.pageSize" @change="handlePageSizeChange">
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
        <span class="pagination-info">共 {{ pagination.total }} 条记录</span>
      </div>
    </div>
  </div>
</template>

<script>
import { productionMaterialRequisitionApi } from '@/api/productionMaterialRequisition'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ProductionPicking',
  data() {
    return {
      loading: false,
      pickingList: [],
      searchForm: {
        keyword: '',
        approvalStatus: '',
        username: '',
        startDate: '',
        endDate: ''
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        pages: 0
      }
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.pickingList.length > 0 && this.pickingList.every(item => item.selected);
      },
      set(value) {
        this.pickingList.forEach(item => {
          item.selected = value;
        });
      },
    },
    selectedItems() {
      return this.pickingList.filter(item => item.selected);
    }
  },
  mounted() {
    console.log('组件已挂载，开始加载数据...');
    this.loadData();
  },
  methods: {
    // 加载数据
    async loadData() {
      try {
        this.loading = true;
        const params = {
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.getSearchParams()
        };
        
        console.log('请求参数:', params);
        
        const response = await productionMaterialRequisitionApi.getPage(params);
        console.log('API响应:', response);
        
        // 处理不同的响应数据结构
        let data = response.data;
        
        // 如果response.data是分页对象
        if (data && typeof data === 'object') {
          console.log('响应数据结构:', data);
          
          // 尝试不同的数据结构
          let records = data.records || data.data || data.list || [];
          
          // 如果data本身就是数组
          if (Array.isArray(data)) {
            records = data;
          }
          
          this.pickingList = records.map(item => ({
            // 原始数据保持不变
            ...item,
            // 添加字段映射，支持snake_case到camelCase的转换
            id: item.id || item.ID || item.requisition_id || item.pk_id || item.pkId,
            requisitionNo: item.requisition_no || item.requisitionNo,
            approvalStatus: item.approval_status !== undefined ? item.approval_status : item.approvalStatus,
            requisitionDate: item.requisition_date || item.requisitionDate,
            totalQuantity: item.total_quantity || item.totalQuantity,
            warehouseReceipt: item.warehouse_receipt || item.warehouseReceipt,
            productionWorkOrder: item.production_work_order || item.productionWorkOrder,
            workOrderCode: item.work_order_code || item.workOrderCode || (item.production_work_order || item.productionWorkOrder || '').split(' ').pop(),
            username: item.username,
            remarks: item.remarks || item.remark,
            selected: false
          }));
          
          console.log('处理后的数据列表:', this.pickingList);
        
        // 调试：检查第一条记录的所有属性
        if (this.pickingList.length > 0) {
          console.log('=== 数据结构分析 ===');
          console.log('第一条记录的所有属性:', Object.keys(this.pickingList[0]));
          console.log('第一条记录完整数据:', this.pickingList[0]);
          console.log('原始API数据第一条记录:', records[0]);
          console.log('原始API数据第一条记录的属性:', Object.keys(records[0] || {}));
          console.log('=== 分析结束 ===');
        }
          
          this.pagination = {
            current: data.current || data.pageNum || 1,
            pageSize: data.size || data.pageSize || 10,
            total: data.total || records.length || 0,
            pages: data.pages || Math.ceil((data.total || records.length) / (data.size || data.pageSize || 10)) || 1
          };
        } else {
          console.warn('响应数据格式异常:', data);
          this.pickingList = [];
        }
        
      } catch (error) {
        console.error('加载数据失败:', error);
        console.error('错误详情:', error.response);
        
        // 显示更详细的错误信息
        if (error.response) {
          const status = error.response.status;
          const message = error.response.data?.message || error.message;
          ElMessage.error(`请求失败 (${status}): ${message}`);
        } else if (error.request) {
          ElMessage.error('网络请求失败，请检查后端服务是否启动');
        } else {
          ElMessage.error('加载数据失败，请重试');
        }
      } finally {
        this.loading = false;
      }
    },

    // 获取搜索参数
    getSearchParams() {
      const params = {};
      
      if (this.searchForm.keyword) {
        // 关键词可能匹配领料单号或工单编号
        params.requisitionNo = this.searchForm.keyword;
        params.productionWorkOrder = this.searchForm.keyword;
      }
      
      if (this.searchForm.approvalStatus !== '') {
        params.approvalStatus = parseInt(this.searchForm.approvalStatus);
      }
      
      if (this.searchForm.username) {
        params.username = this.searchForm.username;
      }
      
      if (this.searchForm.startDate) {
        params.startDate = this.searchForm.startDate;
      }
      
      if (this.searchForm.endDate) {
        params.endDate = this.searchForm.endDate;
      }
      
      return params;
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1;
      this.loadData();
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        keyword: '',
        approvalStatus: '',
        username: '',
        startDate: '',
        endDate: ''
      };
      this.pagination.current = 1;
      this.loadData();
    },

    // 分页改变
    handlePageChange(page) {
      if (page < 1 || page > this.pagination.pages) return;
      this.pagination.current = page;
      this.loadData();
    },

    // 页面大小改变
    handlePageSizeChange() {
      this.pagination.current = 1;
      this.loadData();
    },

    // 获取页码数组
    getPageNumbers() {
      const pages = [];
      const total = this.pagination.pages;
      const current = this.pagination.current;
      
      if (total <= 7) {
        for (let i = 1; i <= total; i++) {
          pages.push(i);
        }
      } else {
        if (current <= 4) {
          for (let i = 1; i <= 5; i++) {
            pages.push(i);
          }
          pages.push('...');
          pages.push(total);
        } else if (current >= total - 3) {
          pages.push(1);
          pages.push('...');
          for (let i = total - 4; i <= total; i++) {
            pages.push(i);
          }
        } else {
          pages.push(1);
          pages.push('...');
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i);
          }
          pages.push('...');
          pages.push(total);
        }
      }
      
      return pages.filter(p => p !== '...' || pages.indexOf(p) === pages.lastIndexOf(p));
    },

    // 更新选择状态
    updateSelection() {
      // 触发计算属性更新
    },

    // 新建
    async handleAdd() {
      try {
        // 新建弹窗
        const { value: formData } = await ElMessageBox.prompt(
          `<div style="text-align: left; padding: 5px 0;">
            <div style="display: flex; align-items: center; margin-bottom: 20px; padding: 15px; background: linear-gradient(135deg, #e8f5e8 0%, #d4f4dd 100%); border-radius: 8px; border-left: 4px solid #67c23a;">
              <i class="el-icon-plus" style="color: #67c23a; font-size: 20px; margin-right: 12px;"></i>
              <div style="flex: 1;">
                <div style="font-size: 16px; font-weight: 600; color: #1f2937; margin-bottom: 4px;">新建领料单</div>
                <div style="font-size: 13px; color: #6b7280;">
                  创建新的生产领料申请单，填写完整信息后提交审批
                </div>
              </div>
            </div>
            
            <div style="background: #f0f9ff; padding: 15px; border-radius: 8px; border-left: 4px solid #409eff; margin-bottom: 20px;">
              <div style="display: flex; align-items: center; margin-bottom: 10px;">
                <i class="el-icon-info" style="color: #409eff; font-size: 16px; margin-right: 8px;"></i>
                <span style="font-size: 14px; font-weight: 500; color: #374151;">输入格式说明</span>
              </div>
              <div style="font-size: 13px; color: #6b7280; line-height: 1.6; margin-bottom: 12px;">
                请按照以下格式输入信息，用逗号分隔各字段：
              </div>
              <div style="background: white; padding: 12px; border-radius: 4px; border: 1px solid #e1e5e9;">
                <div style="font-size: 13px; color: #374151; margin-bottom: 6px;">
                  <strong>格式：</strong> <code style="background: #f3f4f6; padding: 2px 6px; border-radius: 3px; color: #1f2937;">领料单号,申请人,备注</code>
                </div>
                <div style="font-size: 13px; color: #67c23a; font-weight: 500;">
                  <strong>示例：</strong> SCLL2024010001,张三,紧急生产需求
                </div>
              </div>
            </div>
            
            <div style="margin-bottom: 12px;">
              <div style="display: flex; align-items: center; margin-bottom: 8px;">
                <i class="el-icon-edit-outline" style="color: #6b7280; font-size: 14px; margin-right: 6px;"></i>
                <span style="font-size: 14px; font-weight: 500; color: #374151;">领料单信息</span>
              </div>
              <div style="font-size: 12px; color: #9ca3af;">
                请在下方输入框中按格式输入完整的领料单信息
              </div>
            </div>
          </div>`,
          '',
          {
            confirmButtonText: '创建领料单',
            cancelButtonText: '取消',
            inputPlaceholder: '请输入：领料单号,申请人,备注\n例如：SCLL2024010001,张三,紧急生产需求',
            inputValidator: (value) => {
              if (!value || value.trim() === '') {
                return '请输入领料单信息';
              }
              const parts = value.split(',');
              if (parts.length < 2) {
                return '请按格式输入：领料单号,申请人,备注（至少包含领料单号和申请人）';
              }
              if (!parts[0].trim()) {
                return '领料单号不能为空';
              }
              if (!parts[1].trim()) {
                return '申请人不能为空';
              }
              return true;
            },
            dangerouslyUseHTMLString: true,
            customClass: 'custom-add-dialog'
          }
        );
        
        const [requisitionNo, username, remarks] = formData.split(',').map(s => s.trim());
        
        // 构建新建数据
        const newData = {
          requisitionNo: requisitionNo,
          username: username,
          remarks: remarks || '',
          approvalStatus: 0, // 默认待审核
          requisitionDate: new Date().toISOString().split('T')[0], // 今天日期
          totalQuantity: 0
        };
        
        // 由于没有有效的数字ID，暂时只在前端添加显示
        // 实际项目中需要调用后端API: await productionMaterialRequisitionApi.add(newData);
        
        // 添加到前端列表
        const newItem = {
          ...newData,
          id: Date.now(), // 临时ID
          requisition_no: newData.requisitionNo,
          approval_status: newData.approvalStatus,
          requisition_date: newData.requisitionDate,
          total_quantity: newData.totalQuantity,
          warehouse_receipt: '',
          production_work_order: '',
          selected: false
        };
        
        this.pickingList.unshift(newItem);
        
        ElMessage({
          message: `领料单 ${requisitionNo} 创建成功！`,
          type: 'success',
          duration: 3000,
          showClose: true
        });
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('新建失败:', error);
          ElMessage.error('新建失败: ' + (error.message || '未知错误'));
        }
      }
    },

    // 查看详情
    async handleView(item) {
      try {
        console.log('查看详情，item:', item);
        
        // 创建格式化的详情内容
        const detailHtml = `
          <div style="text-align: left; line-height: 1.8; font-size: 14px;">
            <div style="margin-bottom: 12px;">
              <span style="display: inline-block; width: 80px; font-weight: bold; color: #606266;">领料单号:</span>
              <span style="color: #409eff; font-weight: 500;">${item.requisition_no || item.requisitionNo || '-'}</span>
            </div>
            <div style="margin-bottom: 12px;">
              <span style="display: inline-block; width: 80px; font-weight: bold; color: #606266;">审批状态:</span>
              <span style="color: ${this.getStatusColor(item.approval_status || item.approvalStatus)}; font-weight: 500;">
                ${this.getStatusText(item.approval_status || item.approvalStatus)}
              </span>
            </div>
            <div style="margin-bottom: 12px;">
              <span style="display: inline-block; width: 80px; font-weight: bold; color: #606266;">领料日期:</span>
              <span>${this.formatDate(item.requisition_date || item.requisitionDate)}</span>
            </div>
            <div style="margin-bottom: 12px;">
              <span style="display: inline-block; width: 80px; font-weight: bold; color: #606266;">领料总数:</span>
              <span style="color: #67c23a; font-weight: 500;">${item.total_quantity || item.totalQuantity || '-'}</span>
            </div>
            <div style="margin-bottom: 12px;">
              <span style="display: inline-block; width: 80px; font-weight: bold; color: #606266;">出库单:</span>
              <span>${item.warehouse_receipt || item.warehouseReceipt || '-'}</span>
            </div>
            <div style="margin-bottom: 12px;">
              <span style="display: inline-block; width: 80px; font-weight: bold; color: #606266;">生产工单:</span>
              <span style="color: #909399;">${item.production_work_order || item.productionWorkOrder || '-'}</span>
            </div>
            <div style="margin-bottom: 12px;">
              <span style="display: inline-block; width: 80px; font-weight: bold; color: #606266;">申请人:</span>
              <span>${item.username || '-'}</span>
            </div>
            <div style="margin-bottom: 8px;">
              <span style="display: inline-block; width: 80px; font-weight: bold; color: #606266; vertical-align: top;">备注:</span>
              <span style="color: #909399; word-break: break-all;">${item.remarks || '无'}</span>
            </div>
          </div>
        `;
        
        await ElMessageBox.alert('', '领料单详情', {
          confirmButtonText: '确定',
          type: 'info',
          dangerouslyUseHTMLString: true,
          message: detailHtml,
          customStyle: {
            width: '500px'
          }
        });
        
      } catch (error) {
        console.error('查看详情失败:', error);
        ElMessage.error('查看详情失败: ' + (error.message || '未知错误'));
      }
    },

    // 编辑
    async handleEdit(item) {
      try {
        console.log('编辑记录，item:', item);
        
        // 编辑弹窗
        const { value: newRemarks } = await ElMessageBox.prompt(
          `<div style="text-align: left; padding: 5px 0;">
            <div style="display: flex; align-items: center; margin-bottom: 20px; padding: 15px; background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%); border-radius: 8px; border-left: 4px solid #409eff;">
              <i class="el-icon-edit" style="color: #409eff; font-size: 20px; margin-right: 12px;"></i>
              <div style="flex: 1;">
                <div style="font-size: 16px; font-weight: 600; color: #1f2937; margin-bottom: 8px;">编辑领料单</div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; font-size: 13px; color: #6b7280;">
                  <div><span style="color: #374151;">单号:</span> <span style="color: #409eff; font-weight: 500;">${item.requisition_no || item.requisitionNo}</span></div>
                  <div><span style="color: #374151;">状态:</span> <span style="color: ${this.getStatusColor(item.approval_status || item.approvalStatus)}; font-weight: 500;">${this.getStatusText(item.approval_status || item.approvalStatus)}</span></div>
                  <div><span style="color: #374151;">日期:</span> <span>${this.formatDate(item.requisition_date || item.requisitionDate)}</span></div>
                  <div><span style="color: #374151;">总数:</span> <span style="color: #67c23a; font-weight: 500;">${item.total_quantity || item.totalQuantity || '-'}</span></div>
                  <div><span style="color: #374151;">出库单:</span> <span>${item.warehouse_receipt || item.warehouseReceipt || '-'}</span></div>
                  <div><span style="color: #374151;">申请人:</span> <span>${item.username || '-'}</span></div>
                </div>
                <div style="margin-top: 8px; font-size: 13px; color: #6b7280;">
                  <span style="color: #374151;">工单:</span> <span style="color: #909399;">${item.production_work_order || item.productionWorkOrder || '-'}</span>
                </div>
              </div>
            </div>
            
            <div style="margin-bottom: 12px;">
              <div style="display: flex; align-items: center; margin-bottom: 8px;">
                <i class="el-icon-edit-outline" style="color: #6b7280; font-size: 14px; margin-right: 6px;"></i>
                <span style="font-size: 14px; font-weight: 500; color: #374151;">备注信息</span>
              </div>
              <div style="font-size: 12px; color: #9ca3af; margin-bottom: 8px;">
                请在下方文本框中输入新的备注信息，支持多行文本
              </div>
            </div>
          </div>`,
          '',
          {
            confirmButtonText: '保存修改',
            cancelButtonText: '取消',
            inputValue: item.remarks || '',
            inputPlaceholder: '请输入备注信息...\n\n支持多行文本输入\n例如：\n- 紧急领料\n- 生产计划变更\n- 其他说明',
            inputType: 'textarea',
            dangerouslyUseHTMLString: true,
            customClass: 'custom-edit-dialog',
            beforeClose: (action, instance, done) => {
              if (action === 'confirm') {
                if (instance.inputValue && instance.inputValue.trim().length > 200) {
                  ElMessage.warning('备注信息不能超过200个字符');
                  return;
                }
              }
              done();
            }
          }
        );
        
        // 由于没有有效的数字ID，暂时只在前端更新显示
        // 实际项目中需要后端提供正确的ID字段或使用其他标识符
        const index = this.pickingList.findIndex(listItem => 
          (listItem.requisition_no || listItem.requisitionNo) === (item.requisition_no || item.requisitionNo)
        );
        
        if (index !== -1) {
          this.pickingList[index].remarks = newRemarks;
          ElMessage({
            message: `领料单 ${item.requisition_no || item.requisitionNo} 的备注信息已更新`,
            type: 'success',
            duration: 3000,
            showClose: true
          });
        } else {
          ElMessage.error('未找到对应记录');
        }
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('编辑失败:', error);
          ElMessage.error('编辑失败: ' + (error.message || '未知错误'));
        }
      }
    },

    // 删除
    async handleDelete(item) {
      try {
        console.log('删除记录，item:', item);
        
        const requisitionNo = item.requisition_no || item.requisitionNo;
        
        await ElMessageBox.confirm(
          `<div style="text-align: center;">
            <div style="margin-bottom: 15px;">
              <i class="el-icon-warning" style="color: #e6a23c; font-size: 24px;"></i>
            </div>
            <div style="font-size: 16px; color: #606266; margin-bottom: 8px;">确定要删除以下领料单吗？</div>
            <div style="font-size: 14px; color: #409eff; font-weight: bold;">${requisitionNo}</div>
            <div style="font-size: 12px; color: #909399; margin-top: 8px;">删除后无法恢复，请谨慎操作</div>
          </div>`,
          '确认删除',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
            customClass: 'custom-message-box'
          }
        );

        // 由于没有有效的数字ID，暂时只在前端删除显示
        // 实际项目中需要后端提供正确的ID字段或使用领料单号作为删除标识
        const index = this.pickingList.findIndex(listItem => 
          (listItem.requisition_no || listItem.requisitionNo) === requisitionNo
        );
        
        if (index !== -1) {
          this.pickingList.splice(index, 1);
          ElMessage.success('记录已删除（仅前端显示，实际删除需要后端支持正确的ID）');
        } else {
          ElMessage.error('未找到对应记录');
        }
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          ElMessage.error('删除失败: ' + (error.message || '未知错误'));
        }
      }
    },

    // 批量删除
    async handleBatchDelete() {
      if (this.selectedItems.length === 0) {
        ElMessage.warning('请选择要删除的记录');
        return;
      }

      try {
        const selectedList = this.selectedItems.map(item => 
          `<li style="margin: 4px 0; color: #409eff;">${item.requisition_no || item.requisitionNo}</li>`
        ).join('');

        await ElMessageBox.confirm(
          `<div style="text-align: left;">
            <div style="text-align: center; margin-bottom: 15px;">
              <i class="el-icon-warning" style="color: #e6a23c; font-size: 24px;"></i>
            </div>
            <div style="font-size: 16px; color: #606266; margin-bottom: 12px; text-align: center;">
              确定要删除以下 <span style="color: #f56c6c; font-weight: bold;">${this.selectedItems.length}</span> 条领料单吗？
            </div>
            <div style="max-height: 200px; overflow-y: auto; background: #f5f7fa; padding: 10px; border-radius: 4px; margin: 10px 0;">
              <ul style="margin: 0; padding-left: 20px; font-size: 14px;">
                ${selectedList}
              </ul>
            </div>
            <div style="font-size: 12px; color: #909399; text-align: center; margin-top: 8px;">删除后无法恢复，请谨慎操作</div>
          </div>`,
          '确认批量删除',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
            customClass: 'custom-message-box'
          }
        );

        // 批量删除 - 仅前端操作
        const selectedRequisitionNos = this.selectedItems.map(item => 
          item.requisition_no || item.requisitionNo
        );
        
        this.pickingList = this.pickingList.filter(item => 
          !selectedRequisitionNos.includes(item.requisition_no || item.requisitionNo)
        );
        
        ElMessage.success(`已删除 ${this.selectedItems.length} 条记录（仅前端显示，实际删除需要后端支持正确的ID）`);
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error);
          ElMessage.error('批量删除失败');
        }
      }
    },

    // 状态样式
    statusClass(status) {
      // 处理字符串和数字类型
      const statusNum = parseInt(status);
      if (statusNum === 0) return 'status-pending';
      if (statusNum === 1) return 'status-approved';
      if (statusNum === 2) return 'status-rejected';
      return '';
    },

    // 获取状态文本
    getStatusText(status) {
      // 处理字符串和数字类型
      const statusNum = parseInt(status);
      const statusMap = {
        0: '待审核',
        1: '审核通过',
        2: '审核驳回'
      };
      return statusMap[statusNum] || '未知';
    },

    // 获取状态颜色
    getStatusColor(status) {
      const statusNum = parseInt(status);
      const colorMap = {
        0: '#e6a23c', // 待审核 - 橙色
        1: '#67c23a', // 审核通过 - 绿色
        2: '#f56c6c'  // 审核驳回 - 红色
      };
      return colorMap[statusNum] || '#909399'; // 默认灰色
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      return date.toLocaleDateString('zh-CN');
    },

    // 获取记录的唯一标识
    getItemId(item) {
      // 尝试多种可能的ID字段名
      let itemId = item.id || item.ID || item.Id || item.pk_id || item.pkId || item.primaryKey;
      
      // 如果没有找到ID，尝试使用领料单号作为标识
      if (!itemId) {
        itemId = item.requisition_no || item.requisitionNo;
        console.log('使用领料单号作为ID:', itemId);
      }
      
      // 如果还是没有，尝试其他可能的唯一字段
      if (!itemId) {
        // 可能的其他唯一标识字段
        itemId = item.code || item.number || item.key;
      }
      
      console.log('最终获取到的ID:', itemId, '来源item:', item);
      return itemId;
    },

  },
};
</script>

<style scoped>
.production-picking-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-section {
  display: flex;
  gap: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
}

.filter-item input,
.filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 200px;
}

.filter-buttons {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.work-order-code {
  color: #909399;
  font-size: 12px;
  display: block;
}

.status-pending {
  color: #e6a23c;
}

.status-approved {
  color: #67c23a;
}

.status-rejected {
  color: #f56c6c;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.pagination-info {
  margin-left: 10px;
  color: #606266;
  font-size: 14px;
}

.btn-danger {
  background-color: #f56c6c;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.btn-danger:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

.btn-link {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  padding: 4px 8px;
  font-size: 14px;
}

.btn-link:hover {
  text-decoration: underline;
}

.text-danger {
  color: #f56c6c !important;
}

.text-center {
  text-align: center;
}

.filter-item span {
  margin: 0 8px;
  color: #606266;
}

.filter-item input[type="date"] {
  width: 150px;
}

/* 自定义弹窗样式 */
.custom-message-box {
  border-radius: 8px;
}

.custom-message-box .el-message-box__header {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  padding: 15px 20px;
  border-radius: 8px 8px 0 0;
}

.custom-message-box .el-message-box__title {
  color: white;
  font-weight: 600;
}

.custom-message-box .el-message-box__content {
  padding: 20px;
}

.custom-message-box .el-message-box__btns {
  padding: 15px 20px 20px;
}

.custom-message-box .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  font-weight: 500;
}

.custom-message-box .el-button--primary:hover {
  background: linear-gradient(135deg, #66b1ff 0%, #85ce61 100%);
}

/* 详情弹窗特殊样式 */
.el-message-box__content .detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.el-message-box__content .detail-item:last-child {
  border-bottom: none;
}

.el-message-box__content .detail-label {
  display: inline-block;
  width: 80px;
  font-weight: bold;
  color: #606266;
  flex-shrink: 0;
}

.el-message-box__content .detail-value {
  flex: 1;
  margin-left: 10px;
}

/* 编辑弹窗特殊样式 */
.custom-edit-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.custom-edit-dialog .el-message-box {
  width: 580px;
  max-width: 95vw;
}

.custom-edit-dialog .el-message-box__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  border-radius: 12px 12px 0 0;
}

.custom-edit-dialog .el-message-box__title {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.custom-edit-dialog .el-message-box__headerbtn {
  top: 15px;
  right: 15px;
}

.custom-edit-dialog .el-message-box__headerbtn .el-message-box__close {
  color: white;
  font-size: 18px;
}

.custom-edit-dialog .el-message-box__content {
  padding: 25px;
  background: #fafbfc;
}

.custom-edit-dialog .el-message-box__input {
  margin-top: 15px;
}

.custom-edit-dialog .el-message-box__input input,
.custom-edit-dialog .el-message-box__input textarea {
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  padding: 12px 15px;
  font-size: 14px;
  line-height: 1.5;
  transition: all 0.3s ease;
  background: white;
  resize: vertical;
  min-height: 120px;
}

.custom-edit-dialog .el-message-box__input input:focus,
.custom-edit-dialog .el-message-box__input textarea:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
  outline: none;
}

.custom-edit-dialog .el-message-box__input textarea::placeholder {
  color: #a8adb3;
  line-height: 1.6;
}

.custom-edit-dialog .el-message-box__btns {
  padding: 20px 25px 25px;
  background: #fafbfc;
  border-top: 1px solid #e1e5e9;
}

.custom-edit-dialog .el-button {
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  font-size: 14px;
  transition: all 0.3s ease;
}

.custom-edit-dialog .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.custom-edit-dialog .el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
  transform: translateY(-1px);
}

.custom-edit-dialog .el-button--default {
  background: white;
  border: 2px solid #e1e5e9;
  color: #6b7280;
}

.custom-edit-dialog .el-button--default:hover {
  border-color: #c1c7cd;
  color: #4b5563;
  background: #f9fafb;
}

/* 新建弹窗特殊样式 */
.custom-add-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.custom-add-dialog .el-message-box {
  width: 600px;
  max-width: 95vw;
}

.custom-add-dialog .el-message-box__header {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  padding: 20px;
  border-radius: 12px 12px 0 0;
}

.custom-add-dialog .el-message-box__title {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.custom-add-dialog .el-message-box__headerbtn {
  top: 15px;
  right: 15px;
}

.custom-add-dialog .el-message-box__headerbtn .el-message-box__close {
  color: white;
  font-size: 18px;
}

.custom-add-dialog .el-message-box__content {
  padding: 25px;
  background: #fafbfc;
}

.custom-add-dialog .el-message-box__input {
  margin-top: 15px;
}

.custom-add-dialog .el-message-box__input input,
.custom-add-dialog .el-message-box__input textarea {
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  padding: 12px 15px;
  font-size: 14px;
  line-height: 1.5;
  transition: all 0.3s ease;
  background: white;
  min-height: 80px;
}

.custom-add-dialog .el-message-box__input input:focus,
.custom-add-dialog .el-message-box__input textarea:focus {
  border-color: #10b981;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
  outline: none;
}

.custom-add-dialog .el-message-box__input input::placeholder,
.custom-add-dialog .el-message-box__input textarea::placeholder {
  color: #a8adb3;
  line-height: 1.6;
}

.custom-add-dialog .el-message-box__btns {
  padding: 20px 25px 25px;
  background: #fafbfc;
  border-top: 1px solid #e1e5e9;
}

.custom-add-dialog .el-button {
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  font-size: 14px;
  transition: all 0.3s ease;
}

.custom-add-dialog .el-button--primary {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
}

.custom-add-dialog .el-button--primary:hover {
  background: linear-gradient(135deg, #0d9488 0%, #047857 100%);
  box-shadow: 0 6px 16px rgba(16, 185, 129, 0.5);
  transform: translateY(-1px);
}

.custom-add-dialog .el-button--default {
  background: white;
  border: 2px solid #e1e5e9;
  color: #6b7280;
}

.custom-add-dialog .el-button--default:hover {
  border-color: #c1c7cd;
  color: #4b5563;
  background: #f9fafb;
}
</style>
